// 获取用户的id
function getProductId() {
    let url = location.href
    let param = url.substring(url.indexOf('?') + 1)
    let id = param.split('=')[1]
    return id
}
// 调用接口
function getProductDetail() {
    let id = getProductId()
    // 建立连接
    let xhr = new window.XMLHttpRequest()
    xhr.open('get', `http://api.yuguoxy.com/api/shop/find?id=${id}`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                let res = xhr.responseText
                res = JSON.parse(res)
                if (res.resultCode == 1) {
                    let list = res.resultInfo
                    console.log(list);
                    showGetproduct(list)
                }
            }
        }
    }
}
getProductDetail()

// 渲染数据
// 获取大盒子元素
const showEle = document.querySelector('#glassbox')
// 获取下方图片盒子
const pictureEle = document.querySelector('.pictureBig')
function showGetproduct(list) {
    let strNew = ``
    let strTwo = ``

    strNew = `
        <div class="glass-left">
        <div class="show-box">
            <img src="${list.picture}" alt="">
            <div class="mask"></div>
        </div>
        <ul>
            <li class="active"><img src="${list.list[0]}" alt=""></li>
            <li><img src="${list.list[1]}" alt=""></li>
            <li><img src="${list.list[2]}" alt=""></li>
            <li><img src="${list.list[3]}" alt=""></li>
        </ul>
    </div>

    <div class="glass-right" style="display: none;">
        <img src="${list.picture}" alt="">
    </div>

    <div class="content">
        <h2>${list.product}</h2>
        <p>${list.shop}</p>
        <p class="pri"><span>￥</span>${list.price}</p>
        <p class="two">运费<span>新会员专享收单满38元包邮（限三星自营产品，部分产品不可用！）</span></p>
        <button class="increase">加入购物车</button> <button class="pay">立即购买</button>

    </div>
        `
    strTwo = `
        <h2>商品图片</h2>
        <img src="${list.list[0]}" alt="">
        <img src="${list.list[1]}" alt="">
        <img src="${list.list[2]}" alt="">
        <img src="${list.list[3]}" alt="">
        `
    showEle.innerHTML = strNew
    pictureEle.innerHTML = strTwo
    const divEle = document.querySelector('.show-box')
    const clearEle = document.querySelector('.mask')
    const imgEle = document.querySelector('.glass-right')

    divEle.onmouseover = function () {
        clearEle.style.display = 'block'
        // 鼠标移动时旁边的图出现
        imgEle.style.display = 'block'

    }
    divEle.onmouseout = function () {
        clearEle.style.display = 'none'
        // 鼠标移动时旁边的图消失
        imgEle.style.display = 'none'
    }
    let glass = new Glass('#glassbox')
    glass.setScale()
    glass.onGlass()
    glass.onTab()

    //加入购物车
    test(list)
    // 获取立即购买按钮
    testTwo(list)
}




// 移动图表显示
class Glass {
    constructor(id) {
        this.glassRoot = document.querySelector(id)
        this.showBox = this.glassRoot.querySelector('.show-box') //显示盒子
        this.mask = this.glassRoot.querySelector('.mask') //遮罩层
        this.glassBox = this.glassRoot.querySelector('.glass-right') //放大镜盒子
        this.bigImg = this.glassRoot.querySelector('.glass-right>img') //背景图片
        this.liEle = this.glassRoot.querySelectorAll('ul>li')
        this.showImg = this.glassRoot.querySelector('.show-box>img')
    }
    /**
     * 计算缩放比例
     */
    setScale() {
        let glassBoxWidth = parseInt(window.getComputedStyle(this.glassBox).width)
        let glassBoxHeight = parseInt(window.getComputedStyle(this.glassBox).height)
        let showBoxWidth = parseInt(window.getComputedStyle(this.showBox).width)
        let showBoxHeight = parseInt(window.getComputedStyle(this.showBox).height)

        let maskWidth = parseInt(window.getComputedStyle(this.mask).width)
        let maskHeight = parseInt(window.getComputedStyle(this.mask).height)

        let w = glassBoxWidth * showBoxWidth / maskWidth
        let h = glassBoxHeight * showBoxHeight / maskHeight

        this.bigImg.style.width = w + 'px'
        this.bigImg.style.height = h + 'px'
    }
    onGlass() {
        let _this = this
        this.showBox.addEventListener('mousemove', function (e) {
            _this.bigImg.style.zIndex = 10
            e = e || window.event //事件对象
            let x = e.offsetX - _this.mask.offsetWidth / 2
            let y = e.offsetY - _this.mask.offsetHeight / 2
            //边界检查
            if (x < 0) {
                x = 0
            }
            if (x > _this.showBox.offsetWidth - _this.mask.offsetWidth) {
                x = _this.showBox.offsetWidth - _this.mask.offsetWidth
            }
            if (y < 0) {
                y = 0
            }
            if (y > _this.showBox.offsetHeight - _this.mask.offsetHeight) {
                y = _this.showBox.offsetHeight - _this.mask.offsetHeight
            }
            _this.mask.style.top = y + 'px'
            _this.mask.style.left = x + 'px'

            let maskWidth = parseInt(window.getComputedStyle(_this.mask).width)
            let maskHeight = parseInt(window.getComputedStyle(_this.mask).height)
            let glassBoxWidth = parseInt(window.getComputedStyle(_this.glassBox).width)
            let glassBoxHeight = parseInt(window.getComputedStyle(_this.glassBox).height)
            let moveX = x * glassBoxWidth / maskWidth
            let moveY = y * glassBoxHeight / maskHeight

            //移动背景图片
            _this.bigImg.style.left = -moveX + 'px'
            _this.bigImg.style.top = -moveY + 'px'
        })
    }
    onTab() {
        let _this = this
        for (let i = 0; i < _this.liEle.length; i++) {
            _this.liEle[i].addEventListener('click', function (e) {
                e = e || window.event
                let target = e.target || e.srcElement
                _this.onClear()
                this.classList.add('active')
                let changeEle = target.getAttribute('src')
                _this.showImg.setAttribute('src', `${changeEle}`)
                _this.bigImg.setAttribute('src', `${changeEle}`)
            })
        }
    }
    onClear() {
        for (let i = 0; i < this.liEle.length; i++) {
            this.liEle[i].classList.remove('active')
        }
    }
}



// 点击登录跳转
const loginNow = document.querySelector('.car .loginNow')
loginNow.addEventListener('click', function (e) {
    e = e || window.event
    e.preventDefault()
    location.href = './login.html'
})
// 点击购物车跳转
const carNow = document.querySelector('.backCar a')
carNow.addEventListener('click', function (e) {
    e = e || window.event
    e.preventDefault()
    let user = localStorage.getItem('USER')
    user = JSON.parse(user)
    console.log(user);
    if (!user) {
        alert('您还未登录！')
    } else {
        location.href = './cart.html'
    }
})

// 点击加入购物车
function test(productList) {
    // 点击加入购物车按钮
    const onCar = document.querySelector('.content .increase')
    onCar.addEventListener('click', function (e) {
        // 加入购物车按钮
        e = e || window.event
        let target = e.target || e.srcElement
        // 从local中获取数据
        let dataByL = localStorage.getItem('NEWCARTLIST')
        let data = JSON.parse(dataByL) || []
        // 判断是否加入购物车
        var id = productList.id
        var a = data.find(item => item.id == id)
        if (a) {
            a.num++
            a.singlePrice = a.num * a.price
        } else {
            var str = productList
            let newStr = {
                ...str,
                num: 1,
                singlePrice: productList.price
            }
            data.push(newStr)
        }

        localStorage.setItem('NEWCARTLIST', JSON.stringify(data))
        alert('您的商品在购物车等你哦！')
    })

}

// 点击购买
function testTwo(list) {
    const buyNow = document.querySelector('.content .pay')
    buyNow.addEventListener('click', function () {
        alert('请支付￥' + list.price)
    })
}

function testThr() {
    const indexEle = document.querySelector('#nav .top .logo img')
    indexEle.addEventListener('click', function () {
        location.href = 'index.html'
    })
}
testThr()